package com.tsq.map.provider.util;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@Component
@Data
public class TsqHttpUtil {

    private String key;

    public TsqHttpUtil(String key) {
        this.key = key;
    }

    public  final String DEF_CHATSET = "UTF-8";
    public  final int DEF_CONN_TIMEOUT = 30000;
    public  final int DEF_READ_TIMEOUT = 30000;
    public  String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

    public  <T>Object httpGetRest(String url,T bean){
        Map<String,Object> map = null;
        try {
            map = bean instanceof Map ? ((Map<String, Object>) bean) : BeanUtil.beanToMap(bean);
            formatHumpName(map);
            return httpRest(url, "get",  map);
        }catch (Exception e){
            log.info(e.getMessage());
        }
        return null;
    }


    public  <T>Object httpPostRest(String url,T bean){
        Map<String,Object> map = null;
        try {
            map = bean instanceof Map ? ((Map<String, Object>) bean) : BeanUtil.beanToMap(bean);
            formatHumpName(map);
            return httpRest(url, "post",  map);
        }catch (Exception e){
            log.info(e.getMessage());
        }
        return null;
    }

    private Object httpRest(String url,String method, Map<String,Object> map){
        String jsonObject = null;
        try {
            if (method.equalsIgnoreCase("GET")){
                String uri = (String) urlEncode(map);
                url = url + "?key=" + key + uri;
                jsonObject = HttpRequest.get(url).header("User-agent", userAgent)
                        .setReadTimeout(DEF_READ_TIMEOUT)
                        .setConnectionTimeout(DEF_CONN_TIMEOUT)
                        .execute().body();
            } else if (method.equalsIgnoreCase("POST")){
                url = url + "?key=" + key;
                URLUtil.normalize(url);
                jsonObject = HttpRequest.post(url).header("User-agent", userAgent)
                        .setConnectionTimeout(DEF_CONN_TIMEOUT)
                        .setReadTimeout(DEF_READ_TIMEOUT).body(JSON.toJSONString(map))
                        .execute().body();
            } else {
                System.out.println("暂不支持其他请求方式");
            }
        }catch (Exception e){
            log.info(e.getMessage());
        }
        return jsonObject;
    }

    /**
     * 将MAP参数转url
     * @param data 参数
     * @return url类型参数
     */
    public  Object urlEncode(Map<String,Object> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                if(null == i.getValue()){
                    continue;
                }else {
                    sb.append("&").append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8"));
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /**
     * 将map的key进行驼峰转下划
     * @param map 请求参数
     * @return 转换后的map
     */
    public  Map<String, Object> formatHumpName(Map<String, Object> map) {
        Map<String, Object> newMap = new HashMap<String, Object>();
        Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            String key = entry.getKey();
            String newKey = StrUtil.toUnderlineCase(key);
            newMap.put(newKey, entry.getValue());
        }
        return newMap;
    }
}
